package com.yboot.starter.satoken.config;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.yboot.starter.common.core.utils.GeneralPropertySourceFactory;
import com.yboot.starter.common.core.utils.SpringContextUtils;
import com.yboot.starter.satoken.core.Interceptor.RateLimiterInterceptor;
import com.yboot.starter.satoken.core.dao.SaTokenDaoRedisFastjson;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 功能描述
 *
 * @author yangcs
 * @date 2025/8/22
 */
@AutoConfiguration
@EnableConfigurationProperties(SecurityProperties.class)
@PropertySource(value = "classpath:default-auth-satoken.yml", factory = GeneralPropertySourceFactory.class)
public class SaTokenAutoConfigure implements WebMvcConfigurer {
    private final SecurityProperties securityProperties;

    public SaTokenAutoConfigure(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    /**
     * SaToken 拦截器配置
     */
    @Bean
    @ConditionalOnMissingBean
    public SaInterceptor saInterceptor() {
        return new SaInterceptor(handle -> SaRouter.match("/**")
                .notMatch(securityProperties.getExcludes())
                .check(r -> StpUtil.checkLogin())
        );
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(SpringContextUtils.getBean(SaInterceptor.class))
                .addPathPatterns("/**")
                .excludePathPatterns(securityProperties.getExcludes())
                .order(Ordered.HIGHEST_PRECEDENCE + 200);
        // 注册 RateLimiterInterceptor 限流拦截器
        registry.addInterceptor(new RateLimiterInterceptor())
                .addPathPatterns("/**");
    }

    @Bean
    @ConditionalOnBean(name = {"stringRedisTemplate", "redisTemplate"})
    public SaTokenDao saTokenDao(StringRedisTemplate stringRedisTemplate, RedisTemplate redisTemplate) {
        return new SaTokenDaoRedisFastjson(stringRedisTemplate, redisTemplate);
    }
}
